import { Statistic, Row, Col, Popover, Modal, Image } from 'antd';
import AuthModal, { AuthResult } from '@/pages/pc/components/AuthModal';
import { history, Link, useHistory, useModel } from 'umi';
import styles from './index.less';
import classNames from 'classnames';
import { useEffect, useState } from 'react';
import Reward from '@/pages/pc/components/Reward';
import { useLoginStatus } from '@/hooks/login';
import { allGet } from '@/services/pc';
import VideoPlayerModal from '../VideoPlayer';
import Image2 from '@/pages/pc/components/Image';
import moment from 'moment';
import { formatDateBeForeZeroPoint, isYsClass } from '@/utils';
import { CLASS_TYPE_MAP } from '@/common/const';
import WorkTable from '@/pages/pc/lecturer/upload-courses/components/table';
import MaterialModal from '@/pages/pc/components/MaterialModal';
import { WECHAT_NUMBER } from '@/common/const';

const { Countdown } = Statistic;

const Wxshare = (props) => {
  const { userInfo } = useModel('user');
  let url = `${location.origin}/center/courses/detail/${props.classId}`;
  if (userInfo.uid) {
    url = `${url}?shareuid=${userInfo.uid}`;
  }
  console.log(url);
  const img = `https://www.cgjoy.com/app.php?mod=train&do=qrcode&version=pc1.0&url=${encodeURIComponent(
    url,
  )}`;
  return (
    <div className={styles.wxsharemain}>
      <img loading="lazy" src={img} width="134" height="134" alt="" />
      <div className={styles.title}>
        <img loading="lazy" src={require('./images/icon-wx.png')} alt="" width="19" />
        微信扫码分享
      </div>
    </div>
  );
};

const More = (props) => {
  const { userInfo } = useModel('user');
  const handleEdit = () => {
    history.push(`/center/upload-courses?classid=${props.classId}`);
  };
  return (
    <div className={styles.moremain}>
      <a className={styles.item} href="/contract" target="_blank">
        预览合同
      </a>
      {userInfo.isadmin == 1 && (
        <div className={styles.item} onClick={handleEdit}>
          编辑课程
        </div>
      )}
    </div>
  );
};

interface CourseProps {
  data: any;
  /**
   * 1 秒杀
   * 2 预售
   * 3 正常
   */
  type: 1 | 2 | 3;
  /**
   * 1 学员 废弃
   * 2 讲师 废弃
   * 3 学员学习中心
   */
  role: 1 | 2 | 3;
  onBuy?: () => void;
  onLike?: () => void;
  hasRewrad?: boolean;
  classId?: any;
  className?: string;
  query?: any;
  onClick?: () => void;
  needClient?: boolean;
  clientOk?: boolean;

  /**
   * 赠品数量是否是实时库存
   */
  zpnumRealTime?: boolean;

  // 是否显示审核状态
  showApplyStatus?: boolean;
}
const MyCountdown = ({ onFinish, value }) => {
  const times = (time) => {
    const hour = Math.floor(time / 3600);
    const minute = Math.floor((time - hour * 3600) / 60);
    const second = Math.floor(time - hour * 3600 - minute * 60);
    return {
      hour: hour < 10 ? '0' + hour : hour,
      minute: minute < 10 ? '0' + minute : minute,
      second: second < 10 ? '0' + second : second,
    };
  };
  const [time, setTime] = useState<number>(0);
  const handleCountdown = (_value) => {
    setTime(_value / 1000);
  };
  return (
    <Countdown
      valueRender={() => {
        const t = times(time);
        return (
          <div className={styles.myCountdownValue}>
            <span>{t.hour}</span>:<span>{t.minute}</span>:<span>{t.second}</span>
          </div>
        );
      }}
      className={styles.down}
      value={value}
      onChange={handleCountdown}
      onFinish={onFinish}
    />
  );
};
const typeMap = {
  6: '直播+录像课',
  3: '录像',
  8: '预售课',
  5: '实体教学',
  7: '远程免费视频',
};
const Course: React.FC<CourseProps> = ({
  className,
  type: propsType,
  onBuy,
  onLike,
  role = 1,
  hasRewrad = true,
  children,
  classId = 0,
  query,
  needClient = false,
  clientOk = false,
  zpnumRealTime = false,
  data = {},
  onClick,
  showApplyStatus,
}) => {
  const { userInfo } = useModel('user');
  const [type, setType] = useState(propsType);
  // const deadline = Date.now() + 1000 * 60 * 60 * 24 + 1000 * 30;
  const history = useHistory();
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [workTableVisible, setWorkTableVisible] = useState<boolean>(false);
  const [workTableLoading, setWorkTableLoading] = useState<boolean>(true);
  const handleCountdownFinish = () => {
    setType(3);
  };
  const [materialModalShow, setMaterialModalShow] = useState(false);
  useEffect(() => {
    // const deadline = data?.secskills?.secskilldead ? data?.secskills?.secskilldead * 1000 : 0;
    // if (propsType === 1 && deadline && Date.now() >= deadline) {
    //   setType(3);
    // }
    // 如果是秒杀类型， data?.secskill不存在或者data?.secskill?.stop == 1 就是秒杀没了，要变成正常课程类型3
    if (propsType === 1 && (!data?.secskill || data?.secskill?.stop == 1)) {
      setType(3);
    }
  }, []);
  const renderBottomPrice = () => {
    if (type === 1) {
      return (
        <div className={styles.ms}>
          <div className={styles.title}>全网低价</div>
          <div className={styles.row}>
            <div className={styles.price}>
              <div className={styles.text}>秒杀价</div>¥
              <div className={styles.num}>{data?.secskills?.secskillprice}</div>
            </div>
          </div>
        </div>
      );
    }
    if (type === 2) {
      return (
        <div className={styles.ys}>
          <div className={styles.row}>
            <div className={styles.price}>
              <div className={styles.text}>预售价</div>¥
              <div className={styles.num}>{data?.bookprice}</div>
            </div>
          </div>
        </div>
      );
    }
    return null;
  };

  const renderRightPrice = () => {
    if (role === 3) return null;
    if (type === 1) {
      const deadline = data?.secskills?.secskilldead ? data?.secskills?.secskilldead * 1000 : 0;
      return (
        <div className={styles.momeyWrapper}>
          <div className={styles.preferentialPrice}>
            秒杀价<span className={styles.unit}>¥</span>
            <span className={styles.text}>{data?.secskills?.secskillprice}</span>
            {deadline > 0 && <MyCountdown value={deadline} onFinish={handleCountdownFinish} />}
            {/* <div className={styles.xl}>
            限量：27
          </div> */}
          </div>
        </div>
      );
    }
    if (type === 2) {
      return (
        <div className={classNames(styles.momeyWrapper, styles.ys)}>
          <div className={styles.preferentialPrice}>
            预售价 <span className={styles.unit}>¥</span>
            <span className={styles.text}>{data?.bookprice}</span>
          </div>
        </div>
      );
    }
    if (type === 3) {
      return (
        <div className={classNames(styles.momeyWrapper, styles.pt)}>
          <div className={styles.preferentialPrice}>
            售价 <span className={styles.unit}>¥</span>
            <span className={styles.text}>
              {!needClient ? data.price : clientOk ? data.price : ''}
            </span>
          </div>
        </div>
      );
    }
    return null;
  };

  // 点击购买
  const handleBuyClick = async () => {
    onBuy?.();
  };

  // 点击喜欢
  const handleLikeClick = async () => {
    await allGet({ params: { mod: 'course', do: 'learn', classid: classId, version: 'pc1.0' } });
    onLike?.();
  };

  // 编辑课程
  const handleEditClass = async () => {
    // window.open(`/center/upload-courses?classid=${classId}`);
    history.push(`/center/upload-courses?classid=${classId}`);
  };
  // 添加课时
  const handleAddClass = async () => {
    window.open(`/center/upload-courses?classid=${classId}&tabindex=1`);
  };

  // 布置作业
  const handleAddWorks = async () => {
    console.log(classId);
    await getDetails();
    setWorkTableVisible(true);
  };
  // 获取详情
  const getDetails = async () => {
    setWorkTableLoading(true);
    const response = await allGet({
      params: { mod: 'course', do: 'post', version: 'pc1.0', classid: classId /* classid */ },
    });
    if (response.success) {
      const { chapters = [] } = response.data;
      // console.log(2222, allCl);
      let chapters_1: any[] = [];
      let othersLessons_1: any[] = [];
      chapters.forEach((item, index) => {
        if (Number(item.cid) === 0) {
          othersLessons_1 = (item.children ?? []).map((it, i, arr) => {
            if (i > 0) {
              it.beforeIndex = arr[i - 1].displayorder;
            }
            if (i < arr.length - 1) {
              it.afterIndex = arr[i + 1].displayorder;
            }
            return it;
          });
        } else {
          chapters_1.push({
            ...item,
            children: (item.children ?? []).map((it, i, arr) => {
              if (i > 0) {
                it.beforeIndex = arr[i - 1].displayorder;
              } else if (i < arr.length - 1) {
                it.afterIndex = arr[i + 1].displayorder;
              }
              return it;
            }),
          });
        }
      });
      setDataSource([...chapters_1, ...othersLessons_1]);
      setWorkTableLoading(false);
    }
  };

  // 关闭作业弹窗
  const onCloseWorkTable = () => {
    setWorkTableVisible(false);
    setDataSource([]);
  };
  const hasFreeClass = (chapters = []) => {
    let childrenArr = [];
    chapters.forEach((item: any) => {
      childrenArr = [...childrenArr, ...(item.children || [])];
    });
    const lid = childrenArr.find((item) => item.type === '-1')?.lid;

    return lid;
  };
  const handleDownload = () => {
    setMaterialModalShow(true);
  };

  const handleGoMyWork = () => {
    window.open(`/personal?uid=${userInfo.uid}`);
  };

  const handleLearn = () => {
    // 免认证免签
    if (data.nocontract == 1) {
      return window.open(`/center/video/player/${data.classid}`);
    }
    if (userInfo.verify !== 1) {
      AuthModal.show({
        onSuccess: async (values, type) => {
          window.location.reload();
        },
      });
      return;
    }
    if (data.contract != 1) {
      return AuthResult.show({
        buttonText: '签署合同',
        title: '请先签署合同',
        onClick: () => {
          window.location.href = '/learning?index=3';
        },
      });
    }

    window.open(`/center/video/player/${data.classid}`);
  };

  const handleGoRoom = () => {
    window.open(data.showroom);
  };

  const renderButtons = (data) => {
    // 是否有素材下载
    const hasDownfile =
      (Array.isArray(data?.attachs?.attach) && data?.attachs?.attach.length > 0) ||
      (Array.isArray(data?.attachs?.disk) && data?.attachs?.disk.length > 0);

    const lid = hasFreeClass(data?.chapters);

    if (role === 1) {
      const hasKc = data?.secskill?.stop != 1;
      return data.payed !== true ? (
        <>
          <div className={classNames(styles.button, styles.button2)} onClick={handleLikeClick}>
            <i
              className={classNames(styles.icon, styles.like, {
                [styles.actived]: parseInt(data?.learned) > 0,
              })}
            />
            想学
          </div>
          {lid && (
            <div
              className={classNames(styles.button, styles.button2)}
              onClick={() => window.open(`/center/video/player/${data.classid}?lid=${lid}`)}
            >
              {/* <i className={classNames(styles.icon, styles.kan)} /> */}
              试看课程
            </div>
          )}

          {hasKc ? (
            <div className={classNames(styles.primary, styles.button)} onClick={handleBuyClick}>
              立即购买
            </div>
          ) : (
            <div className={classNames(styles.primary, styles.button, styles.disabled)}>
              库存不足
            </div>
          )}
        </>
      ) : (
        <>
          <div className={classNames(styles.primary, styles.button)} onClick={handleLearn}>
            开始学习
          </div>
          {data.showroom && (
            <div className={classNames(styles.primary, styles.button)} onClick={handleGoRoom}>
              <i className={classNames(styles.icon, styles.jrjs)} />
              进入教室
            </div>
          )}
        </>
      );
    }
    if (role === 2) {
      return (
        <>
          <div className={classNames(styles.primary, styles.button)} onClick={handleAddClass}>
            <i className={classNames(styles.icon, styles.tjks)} />
            添加课时
          </div>
          <div
            className={classNames(styles.ghost, styles.button, styles.kc)}
            onClick={handleEditClass}
          >
            <i className={classNames(styles.icon, styles.bjks)} />
            编辑课程
          </div>
          <i className={styles.line} />
          <div className={classNames(styles.button, styles.small)} onClick={handleAddWorks}>
            布置作业
          </div>
          <div
            className={classNames(styles.button, styles.small)}
            onClick={() => window.open(`/lecturer/works?classId=${classId}`)}
          >
            学员作业
            {data.unratenum > 0 && <div className={styles.tips}>未批改: {data.unratenum}份</div>}
          </div>
        </>
      );
    }
    if (role === 3) {
      return (
        <>
          <div className={classNames(styles.button, styles.button2)} onClick={handleLearn}>
            <i className={classNames(styles.icon, styles.jcgk)} />
            教程观看
          </div>
          {hasDownfile && (
            <div className={classNames(styles.button, styles.button2)} onClick={handleDownload}>
              <i className={classNames(styles.icon, styles.xzsc)} />
              下载素材
            </div>
          )}
          <div className={classNames(styles.button, styles.button2)} onClick={handleGoMyWork}>
            <i className={classNames(styles.icon, styles.mywork)} />
            我的作业
          </div>
          {data.showroom && (
            <div className={classNames(styles.primary, styles.button)} onClick={handleGoRoom}>
              <i className={classNames(styles.icon, styles.jrjs)} />
              进入教室
            </div>
          )}
        </>
      );
    }
    return null;
  };

  const isLogin = useLoginStatus();

  const handleShowVideo = (e) => {
    e.stopPropagation();
    VideoPlayerModal.showList({
      data: [{ url: data.video }],
    });
  };
  const renderYh = () => {
    if (type === 1) return null;
    const arr: any[] = [];
    const { coupons, students } = data;
    if (coupons?.commoncouponamount && coupons?.commoncoupondead) {
      const commoncoupondead = formatDateBeForeZeroPoint(coupons?.commoncoupondead * 1000);
      if (moment().isBefore(moment(commoncoupondead))) {
        arr.push(
          <div className={styles.value} key="commoncouponamount">
            <div className={styles.yhtag}>
              <div className={styles.text}>通用券{coupons.commoncouponamount}元</div>
            </div>
          </div>,
        );
      }
    }
    if (coupons?.sharecouponamount && coupons?.sharecoupondead) {
      const sharecoupondead = formatDateBeForeZeroPoint(coupons?.sharecoupondead * 1000);
      if (moment().isBefore(moment(sharecoupondead))) {
        arr.push(
          <div className={styles.value} key="sharecouponamount1">
            <div className={styles.yhtag}>
              <div className={styles.text}>分享得优惠券{coupons.sharecouponamount}</div>
            </div>
          </div>,
        );
      }
    }
    if (students?.studentreduce && students?.studentdead && userInfo.isstudent) {
      const studentdead = formatDateBeForeZeroPoint(students?.studentdead * 1000);
      if (moment().isBefore(moment(studentdead))) {
        arr.push(
          <div className={styles.value} key="sharecouponamount2">
            <div className={styles.yhtag}>
              <div className={styles.text}>老学员优惠{students.studentreduce}</div>
            </div>
          </div>,
        );
      }
    }
    return arr.length > 0 ? (
      <div className={classNames(styles.row, styles.yh)}>
        <div className={styles.key}>优惠：</div>
        {arr.length > 0 ? arr : '-'}
      </div>
    ) : null;
  };
  const renderZp = (hasRow = false) => {
    const rewards = data.rewards;
    const attachs = data.attachs;
    if (rewards?.type === 'gift' && Array.isArray(rewards?.gifts) && rewards?.gifts?.length > 0) {
      const gifts = rewards?.gifts || [];
      // const giftsPicMap = {};
      // attachs?.gift?.forEach?.((item) => {
      //   giftsPicMap[item.aid] = item;
      // });
      if (zpnumRealTime && gifts.every((item) => item.limit - data.givegifted <= 0)) {
        return null;
      }
      return (
        <div className={styles.zp}>
          <div className={styles.text} style={hasRow ? { marginLeft: 0 } : {}}>
            赠品：
          </div>
          {gifts.map((item) => {
            const num = zpnumRealTime ? item.limit - data.givegifted : item.limit;
            return (
              <div className={styles.item} key={item.aid}>
                <Image2
                  src={item.pic}
                  width="26"
                  height="26"
                  text={
                    <div>
                      <div>购买后联系客服，截图购买订单</div>
                      <div>告知想要的赠品和收货地址</div>
                    </div>
                  }
                  className={styles.img}
                />
                {item.limit && `x${num}`}
              </div>
            );
          })}
        </div>
      );
    }
    if (rewards?.type === 'credit') {
      if (zpnumRealTime && rewards?.limit - data.givegifted <= 0) {
        return null;
      }
      const num = zpnumRealTime ? rewards?.limit - data.givegifted : rewards?.limit;
      return (
        <div className={styles.zp}>
          <div className={styles.text} style={hasRow ? { marginLeft: 0 } : {}}>
            赠品：
          </div>
          <div className={styles.item}>
            <Image
              src={require('./images/iocn-cg-quan.png')}
              alt=""
              className={styles.imgcg}
              rootClassName={styles.previewImg}
            />
            <span className={styles.cg}> {rewards?.amount}CG券</span>x{num}
          </div>
        </div>
      );
    }
    return null;
  };

  const handleClickTitle = () => {
    onClick?.();
  };
  const handleClickPic = () => {
    onClick?.();
  };
  return (
    <div
      className={classNames(
        'cgjoy--course-detail',
        styles.container,
        styles[`course${role}`],
        className,
      )}
    >
      {/* "-2"=>已关闭
        "-1"=>审核中
        "0"=>审核通过
        "1"=>正在开课
        "2"=>已结课
        "3"=>停止出售 */}
      {showApplyStatus && data.status == '-1' && (
        <div className={styles.applyStatusWrapper}>
          <i className={styles.icon} />
          <div className={styles.tips}>课程审核中</div>
          <div className={styles.tips}>联系客服加快审核</div>
          <div className={styles.button} onClick={handleEditClass}>
            编辑课程
          </div>
        </div>
      )}
      {showApplyStatus && data.status === '-2' && (
        <div className={styles.applyStatusWrapper}>
          <i className={styles.iconfail} />
          <div className={styles.tips}>
            课程审核 <span className={styles.fail}>未通过</span>
          </div>
          <div className={styles.tips}>联系客服了解原因</div>
          <div className={styles.button} onClick={handleEditClass}>
            编辑课程
          </div>
        </div>
      )}
      <Modal
        wrapClassName="c-lecturer-chapter-modal-wrap-container"
        visible={workTableVisible}
        footer={false}
        onCancel={onCloseWorkTable}
        destroyOnClose
        width={800}
        maskClosable={false}
      >
        <WorkTable
          key={classId}
          isModal
          loading={workTableLoading}
          classid={classId}
          reload={getDetails}
          dataSource={dataSource}
        />
      </Modal>
      <div className={classNames('cgjoy--course-main', styles.detail)}>
        <div className={styles.left}>
          {data.pic && (
            <img
              loading="lazy"
              className={styles.img}
              src={data.pic}
              alt=""
              onClick={handleClickPic}
            />
          )}
          {data.video && (
            <div className={styles.playWrapper} onClick={handleShowVideo}>
              <i className={styles.play} />
            </div>
          )}
          {role !== 3 && data.fqipay_text && (
            <div className={styles.fq}>
              <div className={styles.text}>{data.fqipay_text}</div>
              {/* <div className={styles.qs}>12期</div> */}
            </div>
          )}
          {(data.type == 6 || isYsClass(data)) && (
            <span className={classNames(styles.tag, { [styles.green]: isYsClass(data) })}>
              {isYsClass(data) ? '预售课' : CLASS_TYPE_MAP[data.type] || ''}
            </span>
          )}
          {renderBottomPrice()}
        </div>
        {/* type 类型 6 => '直播+录像课',3 => '录像',8 => '预售课' 5 => '实体教学',7 => '远程免费视频', */}
        <div className={styles.right}>
          <div>
            <div
              className={classNames(styles.title, 'course-detail-title')}
              onClick={handleClickTitle}
            >
              <h3>{data.name}</h3>
            </div>
            {/* {role !== 3 && (
              <div className={styles.handles}>
                <Popover
                  overlayClassName={styles['sharepopover']}
                  placement="bottom"
                  trigger="hover"
                  content={<Wxshare classId={classId} />}
                  title={() => null}
                >
                  <i className={classNames(styles.item, styles.share)} />
                </Popover>
                {isLogin && (
                  <Popover
                    overlayClassName={styles['morepopover']}
                    placement="bottom"
                    trigger="hover"
                    content={<More classId={classId} />}
                    title={() => null}
                  >
                    <i className={classNames(styles.item, styles.more)} />
                  </Popover>
                )}
              </div>
            )} */}
            {role !== 3 && (
              <div className={styles.nums}>
                <div className={styles.fieds}>
                  <i className={classNames(styles.icon, styles.x)} />
                  <div className={styles.value}>{data.learnnum}人想学</div>
                </div>
                <div className={styles.fieds}>
                  <i className={classNames(styles.icon, styles.y)} />
                  <div className={styles.value}>{data.viewnum}</div>
                </div>
                <div className={classNames(styles.fieds, styles.last)}>
                  <i className={classNames(styles.icon, styles.z)} />
                  <div className={styles.value}>{data.dateline}</div>
                </div>
                <div className={styles.software}>
                  <div className={styles.text}>课程用到的软件：</div>
                  <div className={styles.value} style={{ color: '#fff' }}>
                    {Array.isArray(data.softids) ? data.softids.join('、') : '-'}
                  </div>
                </div>
              </div>
            )}
            {role === 3 && (
              <div className={styles.infotags}>
                <div className={styles.item}>学号:{data.studentnum}</div>
                {data.qqqun && <div className={styles.item}>QQ群：{data.qqqun}</div>}
                {data.weixinteacher && (
                  <div className={styles.item}>
                    微信：{data.weixinteacher} ｜ 添加微信，邀请入微信学习群
                  </div>
                )}
              </div>
            )}
            {role != 3 && (
              <div className={styles.infos}>
                {renderRightPrice()}
                <div className={styles.body}>
                  {type !== 3 && (
                    <div className={styles.row}>
                      <div className={styles.key}>原价：</div>
                      <div className={styles.value} style={{ textDecoration: 'line-through' }}>
                        ¥{data.oldprice}
                      </div>
                    </div>
                  )}
                  {(data?.services?.length > 0 || (type === 2 && renderZp() !== null)) && (
                    <div className={classNames(styles.row, styles.fw)}>
                      <div className={styles.key}>服务：</div>
                      <div className={styles.value}>
                        {data?.services?.split && data.services ? (
                          data.services?.split?.(',').join?.(' · ')
                        ) : (
                          <span style={{ color: '#7688a5' }}>-</span>
                        )}
                      </div>
                      {type === 2 && renderZp()}
                    </div>
                  )}
                  {renderYh()}
                  {type !== 2 && renderZp(true) && (
                    <div className={classNames(styles.row)}>{renderZp(true)}</div>
                  )}
                </div>
              </div>
            )}
          </div>
          <div className={styles.teacherWrapper}>
            <Link
              to={`/teachers/detail/${data.uid}`}
              className={classNames(styles.teacher, 'cgjoy--course-detail-teacher')}
            >
              <i className={styles.avatar} style={{ backgroundImage: `url(${data.avatar})` }} />
              <div className={styles.info}>
                <div className={styles.title}>
                  {data.username} 老师 <div className={styles.iconArrow} />
                </div>
              </div>
            </Link>
            <div className={styles.buttons}>
              {!needClient ? renderButtons(data) : clientOk ? renderButtons(data) : null}
              {hasRewrad && (data.payed || role === 2) && data.invitebuys?.cashbacks > 0 && (
                <Reward
                  data={data.invitebuys}
                  classDetail={data}
                  className={classNames(styles.reward, 'course-detail-reward')}
                />
              )}
            </div>
          </div>
        </div>
      </div>

      {children}
      {materialModalShow && (
        <MaterialModal attachs={data?.attachs} onClose={() => setMaterialModalShow(false)} />
      )}
    </div>
  );
};
export default Course;
